package controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import websocket.ChatConnectionPool;

import db.HibernateUtil;
import db.HooldusteenuseTellimus;

/**
 * Servlet implementation class AdminController
 */
@WebServlet("/admin")
public class AdminController extends BaseController {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AdminController() {
	super();
	// TODO Auto-generated constructor stub
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void get(HttpServletRequest request,
	    HttpServletResponse response, String username)
	    throws ServletException, IOException {
	RequestDispatcher view = request.getRequestDispatcher("/main.jsp");
	List<HooldusteenuseTellimus> tellimused = HibernateUtil
		.getAllTellimused();
	JSONArray array = new JSONArray();
	for (HooldusteenuseTellimus t : tellimused) {
	    JSONObject obj = new JSONObject();
	    obj.put("nr", t.getHooldusteenuseTellimuseNr());
	    obj.put("seisund", t.getHooldusteenuseTellimuseSeisundiLiik().getNimetus());
	    obj.put("nimi", t.getKinnistu().getYyrnik().getEesnimi() + " " +t.getKinnistu().getYyrnik().getPerekonnanimi());
	    obj.put("kinnistu", t.getKinnistu().getAadress());
	    obj.put("teenus", t.getHooldusteenus().getNimi());
	    obj.put("muuda", t.getHooldusteenuseTellimuseNr());
	    array.add(obj);
	}
	request.setAttribute("tellimused", JSONValue.toJSONString(array));
	view.forward(request, response);

    }

    @Override
    protected void post(HttpServletRequest request,
	    HttpServletResponse response, String username)
	    throws ServletException, IOException {
	// TODO Auto-generated method stub

    }

}
